package com.peterelst.draw3D {

	import flash.display.Sprite;

	public class Draw3D
	{
		
		public static var FOV:Number = 250;
		
		public static function convert3DTo2D(pt:Point3D):Point2D
		{
			var scaleFactor:Number = Draw3D.FOV/(Draw3D.FOV+pt.z);
			return new Point2D(pt.x*scaleFactor, pt.y*scaleFactor);
		}
		
		public static function lineTo3D(pt1:Point3D, pt2:Point3D, target:Sprite):void 
		{
			var pt1_2D:Point2D = pt1.to2D();
			var pt2_2D:Point2D = pt2.to2D();
						
			target.graphics.moveTo(pt1_2D.x, pt1_2D.y);
			target.graphics.lineTo(pt2_2D.x, pt2_2D.y);
		}
		
		public static function curveTo3D(pt1:Point3D, pt2:Point3D, pt3:Point3D, target:Sprite):void
		{
			var pt1_2D:Point2D = convert3DTo2D(pt1);
			var pt2_2D:Point2D = convert3DTo2D(pt2);
			var pt3_2D:Point2D = convert3DTo2D(pt3);
			target.graphics.moveTo(pt1_2D.x, pt1_2D.y);
			target.graphics.curveTo(pt2_2D.x, pt2_2D.y, pt3_2D.x, pt3_2D.y);
		}
		
		public static function lineThroughPoints3D(pt1:Point3D, pt2:Point3D, pt3:Point3D, target:Sprite):void
		{
			var pt1_2D:Point2D = convert3DTo2D(pt1);
			var pt3_2D:Point2D = convert3DTo2D(pt3);

		    var cx:Number = (pt2.x*2)-(pt1.x + pt3.x)/2;
		    var cy:Number = (pt2.y*2)-(pt1.y + pt3.y)/2;	
			var cz:Number = (pt2.z*2)-(pt1.z + pt3.z)/2;			
			
			var controlPoint3D:Point3D = new Point3D(cx,cy,cz);
			var controlPoint2D:Point2D = Draw3D.convert3DTo2D(controlPoint3D);
			
			target.graphics.moveTo(pt1_2D.x, pt1_2D.y);
			target.graphics.curveTo(controlPoint2D.x, controlPoint2D.y, pt3_2D.x, pt3_2D.y);
		}
		
		public static function connectPoints3D(pts:Array, target:Sprite):void
		{
			var len:uint = pts.length;
			for(var i:uint=1; i<len; ++i)
			{
				var previousPoint:Point3D = pts[i-1] as Point3D;
				var currentPoint:Point3D = pts[i] as Point3D;
				Draw3D.lineTo3D(previousPoint,currentPoint,target);
			}
		}
		
	}
	
}